package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private EmpMapper empMapper;


    @Override
    public PageResult selectAll(String name, LocalDate begin, LocalDate end, int page, int pageSize) {

        Page<Clazz> pageAll = Page.of(page, pageSize);

        Page<Clazz> pageInfo = lambdaQuery().like(StringUtils.hasLength(name), Clazz::getName, name)
                .ge(begin != null, Clazz::getBeginDate, begin)
                .le(end != null, Clazz::getEndDate, end)
                .page(pageAll);

        List<Integer> masterIds = pageInfo.getRecords()
                .stream()
                .map(Clazz::getMasterId)
                .collect(Collectors.toList());
        //根据提取到的id获取班主任姓名
        List<Emp> empsId = empMapper.selectBatchIds(masterIds);

        pageInfo.getRecords().forEach(clazz -> empsId
                .stream()
                .filter(emp -> emp.getId().equals(clazz.getId()))
                .findFirst()
                .ifPresent(emp -> clazz.setMasterName(emp.getName()))
        );

        return new PageResult(pageInfo.getTotal(), pageInfo.getRecords());
    }

    @Override
    public void insertClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    @Override
    public Clazz selectById(Integer id) {
        Clazz clazz = clazzMapper.selectById(id);
        Integer masterId = clazz.getMasterId();
        Emp emp = empMapper.selectById(masterId);
        clazz.setMasterName(emp.getName());
        //无效更改，不知道接口文档的返回值是什么
        return clazz;
    }

    @Override
    public void updateByClazzId(Clazz clazz) {
        clazzMapper.updateById(clazz);
    }

    @Override
    public void deleteById(Integer id) {
        clazzMapper.deleteById(id);
    }
}
